// 未调试好
#include "./ann.h"

class OPT : public ANN {

// 删除一个神经元
void delCell(int id) {
	// 删除与该神经元有关的边
	for (unsigned i = 0; i < cells[id].in_edge_ids.size(); i++)
		delEdge(cells[id].in_edge_ids[i]);
	for (unsigned i = 0; i < cells[id].out_edge_ids.size(); i++)
		delEdge(cells[id].out_edge_ids[i]);
	if ((unsigned)id == cells.size() - 1) {
		cells.pop_back();
		return;
	}
	// 把最后一个神经元置于当前
	cells[id] = cells[cells.size() - 1];
	cells.pop_back();
	// 修改涉及的边
	for (unsigned i = 0; i < cells[id].in_edge_ids.size(); i++)
		edges[cells[id].in_edge_ids[i]].to = id;
	for (unsigned i = 0; i < cells[id].out_edge_ids.size(); i++)
		edges[cells[id].out_edge_ids[i]].from = id;
}

// 删除一条边
void delEdge(int id) {
	edges[id] = edges[edges.size() - 1];
	edges.pop_back();
	buildInOut();
}

// 优化神经网络
void opt() {
	bool *vis = new bool[cells.size()];
	for (unsigned i = 0; i < cells.size(); i++)
		vis[i] = false;
	queue<int> q;
	for (int i = 0; i < input_cell_num; i++) {
		vis[i] = true;
		q.push(i);
	}
	while (!q.empty()) {
		int x = q.front();
		q.pop();
		for (unsigned i = 0; i < cells[x].out_edge_ids.size(); i++) {
			int y = edges[cells[x].out_edge_ids[i]].to;
			if (!vis[y]) {
				vis[y] = true;
				q.push(y);
			}
		}
	}
	for (unsigned i = 0; i < cells.size(); i++)
		if (!vis[i])
			cells[i].del = true;
	delete[] vis;
	for (unsigned i = 0; i < cells.size(); i++)
		while (cells[i].del) {
			if (cells[i].category != 0)
				break;
			delCell(i);
		}
}

};